import axios, {  type AxiosRequestHeaders } from 'axios';
import { useTokenStore } from '@/stores/mytoken';
import { refreshToken } from '@/api/users';
import router from '@/router/index';
import { ElMessage } from 'element-plus';


const request = axios.create({
  // baseURL:import.meta.env.VITE_BASE_URL
})

request.interceptors.request.use(config => {
  if (!config.headers) {
    config.headers = {} as AxiosRequestHeaders
  }

  const store = useTokenStore()
  config.headers.Authorization = store.token.access_token

  return config
})

// 响应拦截器
request.interceptors.response.use(response => {
  return response
}, async error => {
  if (error.response.status === 401) {
    // 刷新token
    const {data} = await refreshToken()
    if (data.success) {
      // 保存新token
      useTokenStore().saveToken(data.content)
      // 重新请求之前接口,并且把结果返回
      return request(error.config)
    } else {
      // 跳转到 login
      ElMessage.error("token过期")
      router.push({name:"login"})
      return
    }
  }

  return Promise.reject(error)
})

export default request